package xyz.iguilty.documents.excel.view;


import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlEngine;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.util.JxlsHelper;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.view.AbstractTemplateView;
import xyz.iguilty.documents.common.constant.DocumentConstant;
import xyz.iguilty.documents.common.utils.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 另一个模板导出工具jxls待定
 */
public class ExcelTemplateView extends AbstractTemplateView {
    @Override
    protected void renderMergedTemplateModel(Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try (InputStream templateStream = new ClassPathResource(Objects.requireNonNull(this.getUrl())).getInputStream();
             ServletOutputStream outputStream = response.getOutputStream()
        ) {
            Context context = new Context(map);
            String filename = String.format("%s_%s.xls", map.containsKey(DocumentConstant.FILENAME) ? String.valueOf(map.get(DocumentConstant.FILENAME)) : this.getBeanName(), new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            JxlsHelper jxlsHelper = JxlsHelper.getInstance();
            Transformer transformer = jxlsHelper.createTransformer(templateStream, outputStream);
            JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
            Map<String, Object> functions = new HashMap<>();
            functions.put("Date", new DateUtil());
            functions.put("Dict", new DictUtil());
            functions.put("Resource", new ResourceUtil());
            JexlBuilder jexlBuilder = new JexlBuilder();
            jexlBuilder.namespaces(functions);
            JexlEngine jexlEngine = jexlBuilder.create();
            evaluator.setJexlEngine(jexlEngine);
            jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);
        }
    }

    @Override
    public boolean checkResource(Locale locale){
        boolean isExist = false;
        try {
            isExist = new ClassPathResource(Objects.requireNonNull(this.getUrl())).getFile().exists();
        } catch (IOException ignored) {
        }
        return isExist;
    }
}
